import axios from 'axios'

/* eslint-disable no-console */
// @ts-check

export default class RtcPlayer {
  /** @param {HTMLVideoElement} videoEl */
  constructor(videoEl) {
    this.pc = new RTCPeerConnection(null)
    // @ts-ignore
    this.pc.onaddstream = event => {
      videoEl.srcObject = event.stream
    }
    return this
  }

  async play(streamUrl) {
    this.pc.addTransceiver('audio', { direction: 'recvonly' })
    this.pc.addTransceiver('video', { direction: 'recvonly' })

    const offer = await this.pc.createOffer()
    await this.pc.setLocalDescription(offer)

    const apiUrl = this._urlFromStream(streamUrl)
    const data = {
      api: apiUrl,
      streamurl: streamUrl,
      clientip: null,
      sdp: offer.sdp,
    }
    console.log('Generated offer:', data)

    const session = await axios
      .post(apiUrl, JSON.stringify(data))
      .then(res => res.json())
      .then(data => {
        console.log('Got answer:', data)
        return data
      })

    await this.pc.setRemoteDescription(
      new RTCSessionDescription({
        type: 'answer',
        sdp: session.sdp,
      })
    )

    return session
  }

  close() {
    this.pc.close()
  }

  _urlFromStream(streamUrl) {
    const url = new URL(streamUrl.replace(/(^rtmp:\/\/|^webrtc:\/\/|^rtc:\/\/)/, 'http://'))
    const protocol = url.protocol.replace(/:$/, '')
    const schema = streamUrl.substr(0, streamUrl.indexOf('://'))

    const enumPort = {
      http: 80,
      https: 443,
      rtmp: 1935,
    }
    const enumSchemaPort = {
      'webrtc-https': 433,
      'rtc-https': 433,
    }
    const port = url.port || enumPort[schema] || enumSchemaPort[`${schema}-${protocol}`] || 1985
    return protocol + '://' + url.hostname + ':' + port + '/rtc/v1/play/'
  }
}
